package com.game.chessnew;

import com.game.chessgame.Player;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ChessPanel extends JPanel {
    private final Board board;
    private int selectedX = -1, selectedY = -1;

    public ChessPanel() {
        setLayout(new GridLayout(8, 8));
        board = new Board();
        board.initialize();

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                add(new ChessCell(i, j));
            }
        }

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = e.getX() / 80;
                int y = e.getY() / 80;

                if (selectedX == -1 && selectedY == -1) {
                    // 选择棋子
                    if (board.getBoard()[y][x] != null && board.getBoard()[y][x].getPlayer() == board.getCurrentPlayer()) {
                        selectedX = x;
                        selectedY = y;
                    }
                } else {
                    // 移动棋子
                    if (board.movePiece(selectedX, selectedY, x, y)) {
                        repaint();
                    }
                    selectedX = -1;
                    selectedY = -1;
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                g.setColor((i + j) % 2 == 0 ? Color.WHITE : Color.GRAY);
                g.fillRect(i * 80, j * 80, 80, 80);
            }
        }

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board.getBoard()[j][i] != null) {
                    g.setColor(board.getBoard()[j][i].getPlayer() == Player.WHITE ? Color.BLACK : Color.WHITE);
                    g.drawString(String.valueOf(board.getBoard()[j][i].getSymbol()), i * 80 + 30, j * 80 + 60);
                }
            }
        }

        if (selectedX != -1 && selectedY != -1) {
            g.setColor(Color.YELLOW);
            g.drawRect(selectedX * 80, selectedY * 80, 80, 80);
        }
    }

    private class ChessCell extends JPanel {
        private final int x, y;

        public ChessCell(int x, int y) {
            this.x = x;
            this.y = y;
            setPreferredSize(new Dimension(80, 80));
        }
    }
}